# -*- coding: utf-8 -*-
import gitee_package
import log_package
import ini_package
from playwright_package import os_package
from gitee_package import re
from playwright_package import time_package
import playwright_package
import excel_package


# 获取gitee数据
def get_gitee_data():
    global ini_opt, ini_opt_school
    try:
        # 连接gitee获取基本数据
        gitee_opt = gitee_package.Gitee_Option('https://gitee.com/zl_b/file_config.git',
                                               "06fbfe091fc755b51084d86966a14cc6")
        main_repo_data = gitee_opt.list_all_files_and_folders('金牛区相关信息')

        # 下载考勤模板
        url = main_repo_data.get('考勤模板.xlsx')
        if url:
            if gitee_opt.download_file('金牛区相关信息/考勤模板.xlsx', 'file/考勤模板.xlsx'):
                log_opt.write_success(f'成功获取gitee数据，【考勤模板.xlsx】下载成功！')
                # 获取ini数据
                url = main_repo_data.get("重要配置.ini")
                if url:
                    da = gitee_opt.get_gitee_repo_file(url)
                    if da:
                        ini_opt.read_ini_string(da)
                        log_opt.write_success(f'成功获取gitee数据，【重要配置.ini】信息成功！')
                        url_2 = main_repo_data.get("学校配置.ini")
                        if url_2:
                            da = gitee_opt.get_gitee_repo_file(url_2)
                            if da:
                                ini_opt_school.read_ini_string(da)
                                log_opt.write_success(f'成功获取gitee数据，【学校配置.ini】信息成功！')
                                url_3 = main_repo_data.get("名单header配置.ini")
                                if url_3:
                                    da = gitee_opt.get_gitee_repo_file(url_3)
                                    if da:
                                        ini_opt_header.read_ini_string(da)
                                        log_opt.write_success(f'成功获取gitee数据，【名单header配置.ini】信息成功！')
                                        return True
                                    else:
                                        raise Exception('获取【名单header配置.ini】信息失败！')
                                else:
                                    raise Exception('未找到-【名单header配置.ini】！')
                            else:
                                raise Exception('获取【学校配置.ini】信息失败！')
                        else:
                            raise Exception('未找到-【学校配置.ini】！')
                    else:
                        raise Exception('获取【重要配置.ini】信息失败！')
                else:
                    raise Exception('未找到-【重要配置.ini】！')
            else:
                raise Exception('【考勤模板.xlsx】下载失败！')
        else:
            raise Exception('未找到-【考勤模板.xlsx】！')

    except Exception as e:
        log_opt.write_error(f'获取gitee出现错误{e}')
        return False


# 数据清洗
def clean_data(file_path):
    """
    清洗数据
    :param ex:excel对象
    :return:
    """
    ex = excel_package.Excel_Option(file_path)
    ex.open_file()
    try:
        for sheet in ex.list_sheets():
            '''删除所有格式'''
            ex.clear_region_format(sheet)

            '''文本居中'''
            ex.modify_region_alignment(sheet, horizontal="center", vertical="center")

            '''删除None列'''
            while True:
                k = ex.get_sheet_headers(sheet)
                # print(k)
                if None in k:

                    # print(sheet)
                    ex.delete_column(sheet, k.index(None) + 1)
                else:
                    break

            '''删除None行'''
            # 配置行
            k = ex.get_column_values(sheet, "A")
            # 如果第一列数据是有行是None就要删除这一行
            while True:
                k = ex.get_column_values(sheet, "A")
                if None in k:
                    # print(k)
                    ex.delete_row(sheet, k.index(None) + 1)
                    # print(sheet)
                else:
                    break

            '''重置索引'''
            rows = ex.get_sheet_max_rows(sheet)
            p = 1
            for i in range(2, rows + 1):
                ex.modify_cell_value(sheet, i, 1, p)
                p += 1
        ex.save_file()
        ex.close_file()
        return True
    except Exception as e:
        ex.close_file()
        return False


# 分割学校名称
def extract_school_name(item):
    if "竞赛" in item:
        match = re.search(r'(\w+)竞赛', item)
        if match:
            return match.group(1)
        else:
            return None

    elif "普" in item:
        match = re.search(r'(\w+)普', item)
        if match:
            return match.group(1)
        else:
            return None
    else:
        return None


# 分割年级
def extract_text_by_nodes(text):
    patterns = [r'(.*?)(普|竞赛)(.*)', r'(.*)(普|竞赛)$']
    for pattern in patterns:
        match = re.search(pattern, text)
        if match:
            return match.group(1), match.group(2), match.group(3)
    return "", "", ""


# 生成名单表-文件
def creat_list_file(file_path):
    ex_main = excel_package.Excel_Option(file_path)
    ex_main.open_file()
    sheet_names = ex_main.list_sheets()
    try:
        if "竞赛模板" in sheet_names:
            sheet_names.remove("竞赛模板")
        if "普模板" in sheet_names:
            sheet_names.remove("普模板")
        # 生产项目学校字典
        school_names = dict()
        for i in ini_opt_school.config.sections():
            school_names[i] = []
        js_sheet_names = []
        pj_sheet_names = []

        # 分类班级
        for sheet in sheet_names:
            if "竞赛" in sheet:
                js_sheet_names.append(sheet)
            else:
                pj_sheet_names.append(sheet)

        # 把班级分至学校
        for school in school_names.keys():
            for op in ini_opt_school.list_section_options(school):
                for pj_sheet in pj_sheet_names:
                    if ini_opt_school.get_section_option(school, op) in extract_school_name(pj_sheet):
                        school_names[school].append(pj_sheet)
                for js_sheet in js_sheet_names:
                    if ini_opt_school.get_section_option(school, op) in extract_school_name(js_sheet):
                        school_names[school].append(js_sheet)

        os_opt.make_file_folder('file/各学校名单')
        # 生成名单表
        for school, sheets in school_names.items():
            # 生成header表头
            ex_1 = excel_package.Excel_Option(f"file/各学校名单/{school}.xlsx")
            ex_1.create_new_excel()
            ex_1.delete_sheet("Sheet")
            for sheet in sheets:
                ex_1.create_new_sheet(sheet)
                headers = []
                if "竞赛" in sheet:
                    # for k, v in ini_opt.config.items():
                    for i, m in ini_opt_header.config["竞赛"].items():
                        if eval(m) == True:
                            headers.append(i)
                            # print(type(eval(m)))
                else:
                    for i, m in ini_opt_header.config["普教"].items():
                        if eval(m) == True:
                            headers.append(i)

                if headers != []:
                    for col, h in enumerate(headers, 1):
                        # print(h, col)
                        ex_1.modify_cell_value(sheet, 1, col, h)

            # 填入数据
            for sheet in sheets:
                # 获取ex_1的headers
                ex_1_headers = ex_1.get_sheet_headers(sheet)
                # print(ex_main.get_sheet_max_rows(sheet))
                for r in range(2, ex_main.get_sheet_max_rows(sheet) + 1):
                    ex_1.insert_row_values(sheet, r, ex_main.get_row_values_as_dict(sheet, r))
                    # print(ex_main.get_row_values_as_dict(sheet, r))
                ex_1.modify_region_alignment(sheet, horizontal="center", vertical="center")
            ex_1.save_file()
            log_opt.write_success(f'【{school}】生成成功！')
        ex_main.close_file()
        return True
    except Exception as e:
        ex_main.close_file()
        return False


# 生成名单表-文件夹
def creat_list_folder(file_path):
    ex_main = excel_package.Excel_Option(file_path)
    ex_main.open_file()
    sheet_names = ex_main.list_sheets()
    try:
        if "竞赛模板" in sheet_names:
            sheet_names.remove("竞赛模板")
        if "普模板" in sheet_names:
            sheet_names.remove("普模板")
        # 生产项目学校字典
        school_names = dict()
        for i in ini_opt_school.config.sections():
            school_names[i] = []
        js_sheet_names = []
        pj_sheet_names = []

        # 分类班级
        for sheet in sheet_names:
            if "竞赛" in sheet:
                js_sheet_names.append(sheet)
            else:
                pj_sheet_names.append(sheet)

        # 把班级分至学校
        for school in school_names.keys():
            for op in ini_opt_school.list_section_options(school):
                for pj_sheet in pj_sheet_names:
                    if ini_opt_school.get_section_option(school, op) in extract_school_name(pj_sheet):
                        school_names[school].append(pj_sheet)
                for js_sheet in js_sheet_names:
                    if ini_opt_school.get_section_option(school, op) in extract_school_name(js_sheet):
                        school_names[school].append(js_sheet)

        os_opt.make_file_folder('file/各学校名单')
        # 生成名单表
        for school, sheets in school_names.items():
            # 创建文件夹
            os_opt.make_file_folder(f"file/各学校名单/{school}")

            for sheet in sheets:
                # 生成header表头
                ex_1 = excel_package.Excel_Option(f"file/各学校名单/{school}/{sheet}.xlsx")
                ex_1.create_new_excel()
                ex_1.delete_sheet("Sheet")
                ex_1.create_new_sheet(sheet)
                headers = []
                if "竞赛" in sheet:
                    # for k, v in ini_opt.config.items():
                    for i, m in ini_opt_header.config["竞赛"].items():
                        if eval(m) == True:
                            headers.append(i)
                            # print(type(eval(m)))
                else:
                    for i, m in ini_opt_header.config["普教"].items():
                        if eval(m) == True:
                            headers.append(i)

                if headers != []:
                    for col, h in enumerate(headers, 1):
                        # print(h, col)
                        ex_1.modify_cell_value(sheet, 1, col, h)
                ex_1.save_file()

            # 填入数据
            for sheet in sheets:
                ex_1 = excel_package.Excel_Option(f"file/各学校名单/{school}/{sheet}.xlsx")
                ex_1.open_file()
                # 获取ex_1的headers
                ex_1_headers = ex_1.get_sheet_headers(sheet)
                # print(ex_main.get_sheet_max_rows(sheet))
                for r in range(2, ex_main.get_sheet_max_rows(sheet) + 1):
                    ex_1.insert_row_values(sheet, r, ex_main.get_row_values_as_dict(sheet, r))
                    # print(ex_main.get_row_values_as_dict(sheet, r))

                ex_1.modify_region_alignment(sheet, horizontal="center", vertical="center")

                ex_1.save_file()
            log_opt.write_success(f'【{school}】生成成功！')

        ex_main.close_file()
        return True
    except Exception as e:
        ex_main.close_file()
        return False


if __name__ == '__main__':
    print('''请选择生成名单模式\n[0]:文件夹版\n[1]:文件版\n为空或者其他值默认为0''')
    user_select_mode = input('请输入您要选择的生成名单模式：\n')

    # 初始化
    time_opt = time_package.Time_Option()
    time_opt.start_timing()
    log_opt = log_package.Logging_Option()
    log_opt.write_info('正在初始化...')
    ini_opt = ini_package.Config_Option()
    ini_opt_school = ini_package.Config_Option()
    ini_opt_header = ini_package.Config_Option()
    os_opt = os_package.Os_Option()
    os_opt.make_file_folder('file')
    os_opt.make_file_folder('log')
    log_opt.write_success('初始化成功！')

    # 获取gitee数据
    try:
        log_opt.write_info('正在获取gitee数据...')
        if get_gitee_data():
            log_opt.write_success('获取gitee数据成功！')
            # print(ini_opt.list_sections())
            file_name = ini_opt.get_section_option('main_xlsx', 'name')
            file_name_url = ini_opt.get_section_option('main_xlsx', 'url')
            # todo 获取钉钉数据
            plw_opt = playwright_package.Playwright_Management()
            log_opt.write_info('正在登陆钉钉...')
            if plw_opt.dingding_login():
                log_opt.write_success('登陆钉钉成功！')
                if plw_opt.dingding_file_download(file_name_url, f'file/{file_name}'):
                    plw_opt.close()
                    # 清洗数据
                    log_opt.write_info(f'正在对file/{file_name}进行数据清洗...')
                    if clean_data(f'file/{file_name}'):
                        log_opt.write_success(f'对file/{file_name}数据清洗成功！')
                    else:
                        raise Exception(f'对file/{file_name}数据清洗失败！')
                    try:
                        user_select_mode = int(user_select_mode)
                    except Exception as e:
                        user_select_mode = 0
                    if user_select_mode == 1:
                        # 生成名单表_文件版
                        log_opt.write_info(f'正在生成名单表_文件版...')
                        if creat_list_file(f'file/{file_name}'):
                            log_opt.write_success('生成名单表_文件版成功！')
                        else:
                            raise Exception('生成名单表_文件版失败！')
                    else:
                        # 生成名单表_文件夹版
                        log_opt.write_info(f'正在生成名单表_文件夹版...')
                        if creat_list_folder(f'file/{file_name}'):
                            log_opt.write_success('生成名单表_文件夹版成功！')
                        else:
                            raise Exception('生成名单表_文件夹版失败！')
                else:
                    raise Exception(f'下载【file/{file_name}】失败！')
            else:
                log_opt.write_error('登陆钉钉失败！')
                raise Exception('获取钉钉数据失败')
        else:
            raise Exception('获取gitee数据失败!')
    except Exception as e:
        log_opt.write_error(f'程序异常：{e}')
    finally:
        log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
        time_opt.timesleep(3)
